#!/usr/bin/python

#Copyright 2012 Elias Farhan
#
#This file is part of Squirrel.
#
#Squirrel is free software: you can redistribute it and/or modify it under the terms of the GNU General 
#Public License as published by the Free Software Foundation, either version 3 of the License, or (at your 
#option) any later version.
#
#Squirrel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
#without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
#See the GNU General Public License for more details.
import pygame
from client.game import game
from client.menu import menu
class Engine():
	def __init__(self):
		self.game = game.Game((0, 0))
		self.menu = menu.Menu()
		self.width, self.height = 0, 0
	def config(self):
		#TODO open a config file
		self.FPS = 30	
		#if the file already exist then don't to create it
		
		screen_info = pygame.display.Info()
		self.height, self.width = screen_info.current_h, screen_info.current_w
		self.screen = pygame.display.set_mode((self.width, self.height), pygame.FULLSCREEN|pygame.DOUBLEBUF)
		self.game.setSize((self.width, self.height))
		#todo1
		self.game.initgame()
		#/todo1
		
	def get_game(self):
		return self.game
		
	def run(self):
		self.game.setSize((self.width, self.height))
		#open config file
		pygame.init()
		self.config()
		self.fpsClock = pygame.time.Clock()
		self.finish = False
		#pygame.mouse.set_visible(0)
		#joystick management
		pygame.joystick.init()
		joystickBool = (pygame.joystick.get_count() != 0)
		if (pygame.joystick.get_count()):
			joystick = pygame.joystick.Joystick(0)
			joystick.init()
			print "number of hats: "+str(joystick.get_numhats())
		while not self.finish:
			self.game.updateScene()
			
			for event in pygame.event.get():
				if joystickBool :
					if event.type == pygame.JOYHATMOTION:
						if (joystick.get_hat(0) == (0, 1)):
							self.game.manageKey("w", False)
						elif(joystick.get_hat(0) == (0, -1)):
							self.game.manageKey("s", False)
						elif(joystick.get_hat(0) == (1, 0)):
							self.game.manageKey("d", False)
						elif(joystick.get_hat(0) == (-1, 0)):
							self.game.manageKey("a", False)
						elif(joystick.get_hat(0) == (0, 0)):
							self.game.manageKey("s", True)
							self.game.manageKey("w", True)
							self.game.manageKey("d", True)
							self.game.manageKey('a', True)
						
				if event.type == pygame.KEYDOWN:
					self.game.manageKey(pygame.key.name(event.key), False)
				elif event.type == pygame.KEYUP:
					if event.key == pygame.K_q:
						self.finish = True
					self.game.manageKey(pygame.key.name(event.key), True)
				elif event.type == pygame.QUIT:
						self.finish = True
				elif event.type == pygame.MOUSEBUTTONDOWN:
					self.game.testmouse(pygame.mouse.get_pos())
			self.screen.fill((0, 0, 0))
			self.game.drawScene(self.screen)
			pygame.display.flip()
			self.fpsClock.tick(self.FPS)

		pygame.quit()
